"use strict";
define(["commonUI","getTime","laydate","echarts", "template","global","select2", "datatables","ztreeExhide"], function (
    commonUI, getTime,laydate, echarts, template,global
) {
    var project=null;
    var user = null;
    var deviceIdArray1 = [];
    var deviceIdArray2 = [];
    var deviceIds1 =null;
    var deviceIds2 =null;
    var standardTable, chart1, chart2;
    var param = {
        pageNumber: 1,
        pageSize: 10
    };
    var app = {
        init: function () {
            if(!global.existCurrProject()){
                alert("请先选择项目");
                return;
            }
            project = global.getCurrProject();
            user = global.getLoginUser();
            this.eventBind();
            // getTime.resize();
            this.initText();
            getTime.getNowDate();
            getTime.getTimeInfo();
            this.initTab1();
            // this.initTab2();
            // this.initTab3();
        },
        /**
         * 渲染文字内容
         */
         initText: function() {
            user = global.getLoginUser();
            //用户名显示
            $(".name").text(user.userName)
        },
        // 实时数据
        initTab1: function () {
            this.initSelect1();
            this.initTable1();
        },
        // 搜索条件初始化
        initSelect1: function () {
            var start = laydate.render({
                elem: '#beginTime',
                showBottom: false,
                eventElem: '.layout-icon-1',
                trigger: 'click',
                // max: 0,
                done: function (value, date, endDate) {
                    end.config.min = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; 
                    end.config.value = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; //将结束日的初始值设定为开始日
                }
            });
            //结束时间
            var end = laydate.render({
                elem: '#endTime',
                showBottom: false,
                eventElem: '.layout-icon-2',
                trigger: 'click',
                // max: 0,
                done: function (value, date) {
                    start.config.max = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; //结束日选好后，重置开始日的最大日期
                }
    
            })
        },
        // 表格初始化
        initTable1: function () {
            standardTable = $("#standard_table").DataTable({
                // 关闭搜索功能
                processing: true,
                searching: false,
                serverSide: true,
                destroy: true,
                ordering: false,
                // scrollY: 600,
                // scrollCollapse: true,
                columns: [{
                    title: "序号",
                    data: "number",
                    width: "100px",
                    render: function (data, type, full) {
                        return "<div class='rank'>" + data + "</div>";
                    }
                }, {
                    title: "名称",
                    data: "deviceName",
                    width: "30%"
                }, {
                    title: "时间",
                    data: "createTime",
                    width: "240px",
                    render: function (data, type, full) {
                        return "<div class=\"text-overflow\" title=\"" + data + "\"><i class='aidicon aidicon-timetable'></i>" + data + "</div>";
                    }
                }, {
                    title: "数值",
                    data: "data",
                    width: "20%"
                }, {
                    title: "单位",
                    data: "unit",
                    width: "30%"
                }],
                columnDefs:[{
                    // targets 同时制定多个列时，可以传递数组（比如[1,2]）;制定所有传"_all"  
                    targets: [1,2,3,4],
                    render: function(data,type,full,meta){//其中data代表本列数据，full代表本行所有数据
                        return "<div class=\"text-overflow\" title=\"" + data + "\">" + data + "</div>";
                    }
                }],
                language: {
                    sEmptyTable: "<div class=\"blank-icon\"><p class=\"msg\"><i class=\"aidicon aidicon-emoticon-sad\"></i> 没有搜到任何数据</p></div>"
                },
                ajax: function (params, callback, setting) {
                    param.pageNumber = (params.start / params.length) + 1;
                    param.pageSize = params.length;
                    param.startTimeSearch = $("#beginTime").val();
                    param.endTimeSearch = $("#endTime").val();
                    param.keySearch = $("#keyWord").val();
                    param.projectId=project.id;
                    global.get("/web/dataReport/realtimeData/list",function (res) {
                        if (res.success) {
                            var obj = {};
                            obj.data = res.data.page.content;
                            obj.draw = params.draw;
                            obj.recordsTotal = res.data.page.totalElements;
                            obj.recordsFiltered = res.data.page.totalElements;
                            callback(obj);
                            }
                        },param);
                },
                initComplete: function (settings, json) {

                }
            });
        },
        // 实时曲线
        initTab2: function () {
            deviceIdArray1 = []
            deviceIds1 = null;
            this.initChart1();
            this.initTree1();
        },
        // 实时曲线--左侧图
        initChart1: function () {
            if(deviceIds1==null){
                return;
            }
            if (chart1) {
                chart1.dispose();
            }
            var list = [], xArr = [], yArr = [];
            var unit = "";
            var name = "";
            var timeLength = 24;
            global.get("/web/dataReport/curve/"+deviceIds1+"?timeMode=0&timeLength="+timeLength,function(response){
                var dates = response.data.dates;
                var legend_data = []
                var series = [];
                unit = response.data.curves[0].unit;
                name = response.data.curves[0].title;
                for(var i=0;i<dates.length;i++){
                    xArr.push(dates[i].substring(11,13)+"时");
                }
                response.data.curves.forEach(curve=>{
                    legend_data.push(curve.title)
                    var serie = {
                        name: curve.title,
                        type: "line",
                        data: curve.curveData,
                        itemStyle: {
                            normal: {
                                borderColor: '#ffffff',
                                borderWidth: 1,
                                opacity: 0.4,
                                barBorderRadius: [5,5,5,5]
                            }
                        }
                    };
                    series.push(serie)
                })
                var option = {
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data:legend_data,
                        top: 60,
                        right: 60,
                        textStyle: {
                            color: "#94d3ff"
                        }
                    },
                    grid: {
                        left: 24,
                        right: 24,
                        bottom: 100,
                        top: 100,
                        containLabel: true
                    },
                    
                    xAxis: [
                        {
                            type: "category",
                            boundaryGap: false,
                            axisTick: {
                                show: false
                            },
                            axisLine: {
                                lineStyle: {
                                    color: "#ffffff",
                                    width:3
                                }
                            },
                            axisLabel: {
                                color: "#94d3ff"
                            },
                            splitLine: {
                                show: false,
                                lineStyle: {
                                    color: "#8cbdd2",
                                    opacity: 0.2
                                }
                            },
                            data: xArr
                        }
                    ],
                    yAxis: [
                        {
                            name: "单位："+unit,
                            nameTextStyle: {
                                color: "#ffffff",
                                fontSize:16,
                                padding: [0, 0 ,20, 0]
                            },
                            type: "value",
                            axisTick: {
                                show: false
                            },
                            axisLine: {
                                show: false,
                                lineStyle: {
                                    color: "#8cbdd2",
                                    opacity: 0.2
                                }
                            },
                            axisLabel: {
                                color: "#94d3ff"
                            },
                            splitLine: {
                                lineStyle: {
                                    type: "dashed",
                                    color: "#8cbdd2",
                                    opacity: 0.2
                                }
                            }
                        }
                    ],
                    series:series,
                    color: ["#f47c47","#b9d0ff","#907dc9","#fddd99"]
                };
                chart1 = echarts.init(document.getElementById("chart1"));
                chart1.setOption(option);
            });
        },
        // 实时曲线--右侧树
        initTree1: function () {
            var setting = {
                check: {
                    enable: true//checkbox
                },
                view: {
                    nameIsHTML: true, //允许name支持html                
                    selectedMulti: false,
                    showLine: false,
                    showIcon: false,
                    addHoverDom: addHoverDom,
                    removeHoverDom: removeHoverDom
                },
                edit: {
                    enable: false,
                    editNameSelectAll: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: onClick,
                    onCheck: zTreeOnCheck,
                }
            };
            global.get("/web/dataReport/categories/"+project.id,function(response){
                var categories = response.data.categories;
                var zNodes = [];
                for(var i=0;i<categories.length;i++){
                    var category = categories[i];
                    var item = {};
                    item.open = true;
                    item.name= category.categoryName;
                    item.id = "p"+category.categoryId
                    item.pId = 0;
                    zNodes.push(item);
                    category.devices.forEach(device=>{
                        var item = {};
                        item.open = false;
                        item.name= device.name;
                        item.id = device.id
                        item.pId = "p"+category.categoryId;
                        zNodes.push(item);
                    });
                }
                $(document).ready(function(){
                    $.fn.zTree.init($("#treeDemo_1"), setting, zNodes);
                    fuzzySearch('treeDemo_1','#key',null,true); //初始化模糊搜索方法
                });
            });

            function zTreeOnCheck(event, treeId, treeNode) {
                // var treeObj = $.fn.zTree.getZTreeObj("treeDemo_1");
                // var nodes = treeObj.getCheckedNodes(true);
                // console.log(nodes)
                
                
                if(deviceIdArray1.indexOf(treeNode.id)>-1){
                    deviceIdArray1.splice(deviceIdArray1.indexOf(treeNode.id),1);
                }else{
                    deviceIdArray1.push(treeNode.id)
                }
                if(deviceIdArray1.length>0){
                    deviceIds1 = deviceIdArray1.join("&");
                    app.initChart1();
                }
                // var treeObj = $.fn.zTree.getZTreeObj("treeDemo_1");
                // var nodes = treeObj.getCheckedNodes(true);
                // console.log(nodes);
            }
            // 鼠标移入树节点
            function addHoverDom(treeId, treeNode) {
                var sObj = $("#" + treeNode.tId + "_span");
                if ($("#ztree_operate_switch_"+treeNode.tId).length > 0) return;
                var addStr = '<div id="ztree_operate_'+ treeNode.tId +'" class="ztree_operate_wrapper"><a class="deleteNode ztree-operate" id="ztree_operate_switch_' + treeNode.tId + '" onfocus="this.blur();">-删除</a></div>';
                sObj.after(addStr);
                var btn = $("#ztree_operate_switch_"+treeNode.tId);
                if (btn) {
                    // 删除
                    $("#ztree_operate_"+treeNode.tId).bind("click", function(e){
                        console.log(treeNode)
                        Dialog.open({
                            title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>确认删除信息</span>",
                            width: 420,
                            height: 'auto',
                            modal: true,
                            content:'<div class="padding-left-large-5">确认需要删除选择的变量吗？删除后不可恢复。</div>',
                            button: [
                                {id:"mybtn1", label:"确认", intent:"primary", focus:true, click:function(){
                                    if(treeNode.pId==null){
                                        //点击父节点
                                        var id = treeNode.id.substring(1)
                                        global.delete("/web/dataReport/deleteCategoryL1/"+id,function(response){
                                            if(response.success){
                                                location.reload()
                                            }else{
                                                alert(response.message)
                                            }
                                        });
                                    }else{
                                        //点击子节点
                                        global.delete("/web/dataReport/deleteCategoryL2/"+treeNode.id,function(response){
                                            if(response.success){
                                                location.reload()
                                            }else{
                                                alert(response.message)
                                            }
                                        });
                                    }
                                }},
                                {id:"mybtn2", label:"取消", click:function(){}}
                            ]
                        });
                    });
                    
                }
            };
            // 鼠标移出
            function removeHoverDom(treeId, treeNode) {
                $("#ztree_operate_"+treeNode.tId).unbind().remove();
            };
            // 点击树节点事件
            function onClick(event, treeId, treeNode) {
                // if(treeNode.pId!=null){
                //     deviceIds1 = "1&2&3";
                //     app.initChart1()
                // }
            }
            /**
             * zTreeId ztree对象的id,不需要#
             * searchField 输入框选择器
             * isHighLight 是否高亮显示，默认高亮，传入false禁用
             * isExpand 是否展开，默认合拢，传入true展开
             */
            function fuzzySearch(zTreeId, searchField, isHighLight, isExpand){
                // 通过id获取树
                var zTreeObj = $.fn.zTree.getZTreeObj(zTreeId);
                if(!zTreeObj){
                    alter("fail to get ztree object");
                }
                // 通过name获取key
                var nameKey = zTreeObj.setting.data.key.name; 
                // 默认为true，仅在使用false时禁用highlight
                isHighLight = isHighLight===false?false:true;
                isExpand = isExpand?true:false; 
                // 使用高亮的情况下允许在node name中使用html
                zTreeObj.setting.view.nameIsHTML = isHighLight; 
            
                var metaChar = '[\\[\\]\\\\\^\\$\\.\\|\\?\\*\\+\\(\\)]'; 
                var rexMeta = new RegExp(metaChar, 'gi');
            
                // keyword过滤
                function ztreeFilter(zTreeObj,_keywords,callBackFunc) {
                    if(!_keywords){
                        // 默认为空
                        _keywords =''; 
                    }
            
                    // 找出匹配节点
                    function filterFunc(node) {
                        if(node && node.oldname && node.oldname.length>0){
                            node[nameKey] = node.oldname; 
                        }
                        zTreeObj.updateNode(node); 
                        if (_keywords.length == 0) {
                            // 如果keyword为空返回所有
                            zTreeObj.showNode(node);
                            zTreeObj.expandNode(node,isExpand);
                            return true;
                        }
                        //转换 node name and keywords 为小写
                        if (node[nameKey] && node[nameKey].toLowerCase().indexOf(_keywords.toLowerCase())!=-1) {
                            if(isHighLight){ 
                                var newKeywords = _keywords.replace(rexMeta,function(matchStr){
                                    return '\\' + matchStr;
                                });
                                node.oldname = node[nameKey]; //store the old name  
                                var rexGlobal = new RegExp(newKeywords, 'gi');
                                node[nameKey] = node.oldname.replace(rexGlobal, function(originalText){
                                    //高亮匹配的文字
                                    var highLightText =
                                        '<span style="color: #2D2F33;background-color: #BEDAFD;">'
                                        + originalText
                                        +'</span>';
                                    return     highLightText;                    
                                });
                                zTreeObj.updateNode(node); 
                            }
                            zTreeObj.showNode(node);
                            return true; 
                        }
            
                        zTreeObj.hideNode(node); 
                        return false; 
                    }
            
                    var nodesShow = zTreeObj.getNodesByFilter(filterFunc); 
                    processShowNodes(nodesShow, _keywords);
                }
                /**
                 * 节点展示前进行处理
                 */
                function processShowNodes(nodesShow,_keywords){
                    if(nodesShow && nodesShow.length>0){
                        if(_keywords.length>0){ 
                            $.each(nodesShow, function(n,obj){
                                var pathOfOne = obj.getPath();
                                if(pathOfOne && pathOfOne.length>0){ 
                                    for(var i=0;i<pathOfOne.length-1;i++){
                                        zTreeObj.showNode(pathOfOne[i]); 
                                        zTreeObj.expandNode(pathOfOne[i],true); 
                                    }
                                }
                            });    
                        }else{ 
                            // 显示所有节点当 _keywords 为空时
                            var rootNodes = zTreeObj.getNodesByParam('level','0');
                            $.each(rootNodes,function(n,obj){
                                zTreeObj.expandNode(obj,true);
                            });
                        }
                    }
                }
                //监听input改变事件
                $(searchField).bind('input propertychange', function() {
                    var _keywords = $(this).val();
                    searchNodeLazy(_keywords); 
                });
                var timeoutId = null;
                // input 改变后执行
                function searchNodeLazy(_keywords) {
                    if (timeoutId) { 
                        //终止前一个
                        clearTimeout(timeoutId);
                    }
                    timeoutId = setTimeout(function() {
                        ztreeFilter(zTreeObj,_keywords); 
                    }, 500);
                }
                // 解决ie9下propertychange backspace不触发的问题 
                // // 判断浏览器类型
                // function BrowserType(){
                //     var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
                //     var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
                //     var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
                //     var isEdge = (userAgent.indexOf("Windows NT 6.1; Trident/7.0;") > -1|| userAgent.indexOf("Windows NT 6.1; WOW64; Trident/7.0;")) && !isIE; //判断是否IE的Edge浏览器
                //     var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
                //     var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器
                //     var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器
            
                //     if (isIE)
                //     {
                //         var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
                //         reIE.test(userAgent);
                //         var fIEVersion = parseFloat(RegExp["$1"]);
                //         if(fIEVersion == 7)
                //         { return "IE7";}
                //         else if(fIEVersion == 8)
                //         { return "IE8";}
                //         else if(fIEVersion == 9)
                //         { return "IE9";}
                //         else if(fIEVersion == 10)
                //         { return "IE10";}
                //         else if(fIEVersion == 11)
                //         { return "IE11";}
                //         else
                //         { return "0"}//IE版本过低
                //     }//isIE end
            
                //     if (isFF) {  return "FF";}
                //     if (isOpera) {  return "Opera";}
                //     if (isSafari) {  return "Safari";}
                //     if (isChrome) { return "Chrome";}
                //     if (isEdge) { return "Edge";}
                // }
                // //  解决ie9下 backspace等事件不触发的问题
                // var myBrowser=BrowserType();
                // console.info("myBrowser:"+myBrowser)
                // if(myBrowser=="IE9"){
                //     $('#key').each(
                //         function () {
                //             var self = $(this);
                //             var intervalName;
                //             self.focus(function(){
                //                 intervalName = setInterval(function () {
                //                     self.trigger("propertychange");
                //                 },3000);
                //             });
                //             self.blur(function()
                //             {
                //                 clearInterval(intervalName);
                //             });
                //         }
                //     );
                // }
            }
        },
        // 历史曲线
        initTab3: function () {
            deviceIdArray2 = []
            deviceIds2 = null;
            this.initSelect2();
            this.initSelect3();
            this.initChart2();
            this.initTree2();
        },
        // 历史曲线--搜索条件初始化
        initSelect2: function () {
            var start = laydate.render({
                elem: '#beginTime2',
                showBottom: false,
                eventElem: '.layout-icon-3',
                trigger: 'click',
                // max: 0,
                done: function (value, date, endDate) {
                    end.config.min = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; 
                    end.config.value = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; //将结束日的初始值设定为开始日
                }
            });
            //结束时间
            var end = laydate.render({
                elem: '#endTime2',
                showBottom: false,
                eventElem: '.layout-icon-4',
                trigger: 'click',
                // max: 0,
                done: function (value, date) {
                    start.config.max = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; //结束日选好后，重置开始日的最大日期
                }
    
            })
            $('.select1').select2({
                //  minimumResultsForSearch设置为-1，去除搜索框 
                minimumResultsForSearch:-1,
                placeholder:"请选择",
                // disabled: true
            });
        },
        initSelect3: function () {
            var start = laydate.render({
                elem: '#beginTime3',
                showBottom: false,
                eventElem: '.layout-icon-5',
                trigger: 'click',
                // max: 0,
                done: function (value, date, endDate) {
                    end.config.min = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; 
                    end.config.value = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; //将结束日的初始值设定为开始日
                }
            });
            //结束时间
            var end = laydate.render({
                elem: '#endTime3',
                showBottom: false,
                eventElem: '.layout-icon-6',
                trigger: 'click',
                // max: 0,
                done: function (value, date) {
                    start.config.max = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; //结束日选好后，重置开始日的最大日期
                }
    
            })
        },
        // 历史曲线--左侧图
        initChart2: function () {
            if(deviceIds2==null){
                return;
            }
            if (chart2) {
                chart2.dispose();
            }
            var list = [], xArr = [], yArr = [];
            var unit = "";
            var name = "";
            var timeLength = 0;
            var type = $(".select1").val();
            var startTime = $("#beginTime2").val();
            var endTime = $("#endTime2").val();
            if(startTime!=null && startTime!=""){
                startTime = "&startTime="+startTime + " 00:00:00";
            }
            if(endTime!=null && endTime!=""){
                endTime = "&endTime="+endTime + " 00:00:00";
            }
            if(type==0){
                timeLength=24;
            }else if(type==1){
                timeLength=30
            }else if(type==2){
                timeLength=30
            }else{
                timeLength=10;
            }
            global.get("/web/dataReport/curve/"+deviceIds2+"?timeMode="+type+"&timeLength="+timeLength+startTime+endTime,function(response){
                var dates = response.data.dates;
                var legend_data = []
                var series = [];
                unit = response.data.curves[0].unit;
                name = response.data.curves[0].title;
                for(var i=0;i<dates.length;i++){
                    if(type==0){
                        xArr.push(dates[i].substring(11,13)+"时");
                    }else if(type==1){
                        xArr.push(dates[i].substring(8,10)+"日");
                    }else if(type==2){
                        xArr.push(dates[i].substring(5,7)+"月");
                    }else{
                        xArr.push(dates[i].substring(0,4)+"年");
                    }
                }
                response.data.curves.forEach(curve=>{
                    legend_data.push(curve.title)
                    var serie = {
                        name: curve.title,
                        type: "line",
                        data: curve.curveData,
                        itemStyle: {
                            normal: {
                                borderColor: '#ffffff',
                                borderWidth: 1,
                                opacity: 0.4,
                                barBorderRadius: [5,5,5,5]
                            }
                        }
                    };
                    series.push(serie)
                })
                var option = {
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data:legend_data,
                        top: 60,
                        right: 60,
                        textStyle: {
                            color: "#94d3ff"
                        }
                    },
                    grid: {
                        left: 24,
                        right: 24,
                        bottom: 100,
                        top: 100,
                        containLabel: true
                    },
                    
                    xAxis: [
                        {
                            type: "category",
                            boundaryGap: false,
                            axisTick: {
                                show: false
                            },
                            axisLine: {
                                lineStyle: {
                                    color: "#ffffff",
                                    width:3
                                }
                            },
                            axisLabel: {
                                color: "#94d3ff"
                            },
                            splitLine: {
                                show: false,
                                lineStyle: {
                                    color: "#8cbdd2",
                                    opacity: 0.2
                                }
                            },
                            data: xArr
                        }
                    ],
                    yAxis: [
                        {
                            name: "单位："+unit,
                            nameTextStyle: {
                                color: "#ffffff",
                                fontSize:16,
                                padding: [0, 0 ,20, 0]
                            },
                            type: "value",
                            axisTick: {
                                show: false
                            },
                            axisLine: {
                                show: false,
                                lineStyle: {
                                    color: "#8cbdd2",
                                    opacity: 0.2
                                }
                            },
                            axisLabel: {
                                color: "#94d3ff"
                            },
                            splitLine: {
                                lineStyle: {
                                    type: "dashed",
                                    color: "#8cbdd2",
                                    opacity: 0.2
                                }
                            }
                        }
                    ],
                    series:series,
                    color: ["#f47c47","#b9d0ff","#907dc9","#fddd99"]
                };
                chart2 = echarts.init(document.getElementById("chart2"));
                chart2.setOption(option);
            });
        },
        // 历史曲线--右侧树
        initTree2: function () {
            var setting = {
                check: {
                    enable: true//checkbox
                },
                view: {
                    nameIsHTML: true, //允许name支持html                
                    selectedMulti: false,
                    showLine: false,
                    showIcon: false,
                    addHoverDom: addHoverDom,
                    removeHoverDom: removeHoverDom
                },
                edit: {
                    enable: false,
                    editNameSelectAll: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: onClick,
                    onCheck: zTreeOnCheck
                }
            };
            global.get("/web/dataReport/categories/"+project.id,function(response){
                var categories = response.data.categories;
                var zNodes = [];
                for(var i=0;i<categories.length;i++){
                    var category = categories[i];
                    var item = {};
                    item.open = true;
                    item.name= category.categoryName;
                    item.id = "p"+category.categoryId
                    item.pId = 0;
                    zNodes.push(item);
                    category.devices.forEach(device=>{
                        var item = {};
                        item.open = false;
                        item.name= device.name;
                        item.id = device.id
                        item.pId = "p"+category.categoryId;
                        zNodes.push(item);
                    });
                }
                $(document).ready(function(){
                    $.fn.zTree.init($("#treeDemo_2"), setting, zNodes);
                    fuzzySearch('treeDemo_2','#key2',null,true); //初始化模糊搜索方法
                });
            });
            // var zNodes =[
            //     { id:1, pId:0, name:"主机", open:true},
            //     { id:11, pId:1, name:"主机1"},
            //     { id:12, pId:1, name:"主机2"},
            //     { id:2, pId:0, name:"水泵", open:true},
            //     { id:21, pId:2, name:"水泵1"},
            //     { id:22, pId:2, name:"水泵"},
            //     { id:3, pId:0, name:"冷却塔", open:true },
            //     { id:31, pId:3, name:"冷却塔"}
            // ];
            // $(document).ready(function(){
            //     $.fn.zTree.init($("#treeDemo_2"), setting, zNodes);
            //     fuzzySearch('treeDemo_2','#key2',null,true); //初始化模糊搜索方法
            // });
            function zTreeOnCheck(event, treeId, treeNode) {
                if(deviceIdArray2.indexOf(treeNode.id)>-1){
                    deviceIdArray2.splice(deviceIdArray2.indexOf(treeNode.id),1);
                }else{
                    deviceIdArray2.push(treeNode.id)
                }
                if(deviceIdArray2.length>0){
                    deviceIds2 = deviceIdArray2.join("&");
                    app.initChart2();
                }
                // var treeObj = $.fn.zTree.getZTreeObj("treeDemo_1");
                // var nodes = treeObj.getCheckedNodes(true);
                // console.log(nodes);
            }
            // 鼠标移入树节点
            function addHoverDom(treeId, treeNode) {
                var sObj = $("#" + treeNode.tId + "_span");
                if ($("#ztree_operate_switch_"+treeNode.tId).length > 0) return;
                var addStr = '<div id="ztree_operate_'+ treeNode.tId +'" class="ztree_operate_wrapper"><a class="deleteNode ztree-operate" id="ztree_operate_switch_' + treeNode.tId + '" onfocus="this.blur();">-删除</a></div>';
                sObj.after(addStr);
                var btn = $("#ztree_operate_switch_"+treeNode.tId);
                if (btn) {
                    // 删除
                    $("#ztree_operate_"+treeNode.tId).bind("click", function(e){
                        console.log(treeNode)
                        Dialog.open({
                            title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>确认删除信息</span>",
                            width: 420,
                            height: 'auto',
                            modal: true,
                            content:'<div class="padding-left-large-5">确认需要删除选择的变量吗？删除后不可恢复。</div>',
                            button: [
                                {id:"mybtn1", label:"确认", intent:"primary", focus:true, click:function(){
                                    if(treeNode.pId==null){
                                        //点击父节点
                                        var id = treeNode.id.substring(1)
                                        global.delete("/web/dataReport/deleteCategoryL1/"+id,function(response){
                                            if(response.success){
                                                location.reload()
                                            }else{
                                                alert(response.message)
                                            }
                                        });
                                    }else{
                                        //点击子节点
                                        global.delete("/web/dataReport/deleteCategoryL2/"+treeNode.id,function(response){
                                            if(response.success){
                                                location.reload()
                                            }else{
                                                alert(response.message)
                                            }
                                        });
                                    }
                                }},
                                {id:"mybtn2", label:"取消", click:function(){}}
                            ]
                        });
                    });
                    
                }
            };
            // 鼠标移出
            function removeHoverDom(treeId, treeNode) {
                $("#ztree_operate_"+treeNode.tId).unbind().remove();
            };
            // 点击树节点事件
            function onClick(event, treeId, treeNode) {
                // if(treeNode.pId!=null){
                //     deviceIds2 = "1&2&3";
                //     app.initChart2()
                // }
            }
            /**
             * zTreeId ztree对象的id,不需要#
             * searchField 输入框选择器
             * isHighLight 是否高亮显示，默认高亮，传入false禁用
             * isExpand 是否展开，默认合拢，传入true展开
             */
            function fuzzySearch(zTreeId, searchField, isHighLight, isExpand){
                // 通过id获取树
                var zTreeObj = $.fn.zTree.getZTreeObj(zTreeId);
                if(!zTreeObj){
                    alter("fail to get ztree object");
                }
                // 通过name获取key
                var nameKey = zTreeObj.setting.data.key.name; 
                // 默认为true，仅在使用false时禁用highlight
                isHighLight = isHighLight===false?false:true;
                isExpand = isExpand?true:false; 
                // 使用高亮的情况下允许在node name中使用html
                zTreeObj.setting.view.nameIsHTML = isHighLight; 
            
                var metaChar = '[\\[\\]\\\\\^\\$\\.\\|\\?\\*\\+\\(\\)]'; 
                var rexMeta = new RegExp(metaChar, 'gi');
            
                // keyword过滤
                function ztreeFilter(zTreeObj,_keywords,callBackFunc) {
                    if(!_keywords){
                        // 默认为空
                        _keywords =''; 
                    }
            
                    // 找出匹配节点
                    function filterFunc(node) {
                        if(node && node.oldname && node.oldname.length>0){
                            node[nameKey] = node.oldname; 
                        }
                        zTreeObj.updateNode(node); 
                        if (_keywords.length == 0) {
                            // 如果keyword为空返回所有
                            zTreeObj.showNode(node);
                            zTreeObj.expandNode(node,isExpand);
                            return true;
                        }
                        //转换 node name and keywords 为小写
                        if (node[nameKey] && node[nameKey].toLowerCase().indexOf(_keywords.toLowerCase())!=-1) {
                            if(isHighLight){ 
                                var newKeywords = _keywords.replace(rexMeta,function(matchStr){
                                    return '\\' + matchStr;
                                });
                                node.oldname = node[nameKey]; //store the old name  
                                var rexGlobal = new RegExp(newKeywords, 'gi');
                                node[nameKey] = node.oldname.replace(rexGlobal, function(originalText){
                                    //高亮匹配的文字
                                    var highLightText =
                                        '<span style="color: #2D2F33;background-color: #BEDAFD;">'
                                        + originalText
                                        +'</span>';
                                    return     highLightText;                    
                                });
                                zTreeObj.updateNode(node); 
                            }
                            zTreeObj.showNode(node);
                            return true; 
                        }
            
                        zTreeObj.hideNode(node); 
                        return false; 
                    }
            
                    var nodesShow = zTreeObj.getNodesByFilter(filterFunc); 
                    processShowNodes(nodesShow, _keywords);
                }
                /**
                 * 节点展示前进行处理
                 */
                function processShowNodes(nodesShow,_keywords){
                    if(nodesShow && nodesShow.length>0){
                        if(_keywords.length>0){ 
                            $.each(nodesShow, function(n,obj){
                                var pathOfOne = obj.getPath();
                                if(pathOfOne && pathOfOne.length>0){ 
                                    for(var i=0;i<pathOfOne.length-1;i++){
                                        zTreeObj.showNode(pathOfOne[i]); 
                                        zTreeObj.expandNode(pathOfOne[i],true); 
                                    }
                                }
                            });    
                        }else{ 
                            // 显示所有节点当 _keywords 为空时
                            var rootNodes = zTreeObj.getNodesByParam('level','0');
                            $.each(rootNodes,function(n,obj){
                                zTreeObj.expandNode(obj,true);
                            });
                        }
                    }
                }
                //监听input改变事件
                $(searchField).bind('input propertychange', function() {
                    var _keywords = $(this).val();
                    searchNodeLazy(_keywords); 
                });
                var timeoutId = null;
                // input 改变后执行
                function searchNodeLazy(_keywords) {
                    if (timeoutId) { 
                        //终止前一个
                        clearTimeout(timeoutId);
                    }
                    timeoutId = setTimeout(function() {
                        ztreeFilter(zTreeObj,_keywords); 
                    }, 500);
                }
            }
        },
        /** 事件绑定 */
        eventBind: function () {
            $(document).on("click", ".tab-nav li", function () {
                $(this).addClass("active").siblings("li").removeClass("active");
                var index = $(this).attr("type");
                $(".tab-wrapper").eq(index-1).removeClass("hidden").siblings(".tab-wrapper").addClass("hidden");
                if(index==1) {
                    app.initTab1()
                } else if(index==2) {
                    app.initTab2()
                } else if(index==3) {
                    app.initTab3()
                }
            })
            $(document).on("click", "#searchBtn1", function () {
                // 改变param1参数
                standardTable.ajax.reload();
            })
            $(document).on("click", "#searchBtn2", function () {
                // 历史 加载
                app.initChart2();
            })
            $(document).on("click", ".checkbox .checkbox-beauty", function(e) {
                if(e.target.nodeName != "SPAN") {
                    if($(this).find("input").prop("checked")) {
                        // console.log(1)
                        $(this).parents(".select-wrap").find(".form-control").attr("disabled", false)
                        $(this).parents(".select-wrap").find("select").attr("disabled", false)
                    } else {
                        // console.log(0)
                        $(this).parents(".select-wrap").find(".form-control").attr("disabled", true)
                        $(this).parents(".select-wrap").find("select").attr("disabled", true)
                    }
                }
            })
            // 新增弹窗--实时曲线
            $(document).on("click", "#add1", function () {
                global.get("/web/dataReport/devicesByProject/"+project.id,response=>{
                    var data=[];
                    response.data.devices.forEach(device=>{
                        var item={};
                        item.id=device.id;
                        item.text=device.name;
                        data.push(item);
                    });
                    Dialog.open({
                        title: "新增",
                        theme: "formDialog",
                        width: 480,
                        height: 320,
                        context: self,
                        content: template("dataFormTpl"),
                        onShow: function () {
                            $('#equipment').select2({
                                //  minimumResultsForSearch设置为-1，去除搜索框 
                                minimumResultsForSearch:-1,
                                placeholder:"请选择",
                                data: data
                            });
                        },
                        onClosed: function () {
                            if ($("#_idlg_mask_").length > 0) {
                                $("#_idlg_mask_").remove();
                            }
                        },
                        button: [{
                            id: "mybtn1",
                            label: "确定",
                            intent: "primary",
                            focus: true,
                            click: function () {
                                var name = $("#name").val();
                                    var equipment = $("#equipment").val();
                                    if(name==null || name.trim()==""){
                                        alert("请输入分类名");
                                        return;
                                    }
                                    var data = {}
                                    data.deviceId=equipment;
                                    data.categoryName=name;
                                    data.projectId=project.id;
                                    global.post("/web/dataReport/saveCategory",function(response){
                                        if(response.success){
                                            location.reload();
                                        }else{
                                            alert(response.message);
                                        }
                                    },JSON.stringify(data));
                            }
                        },
                            {
                                id: "mybtn2",
                                label: "取消",
                                intent: "default",
                                click: function () {
                                    this.close();
                                }
                            }
                        ],
                    });
                });
            })
            // 新增弹窗--历史曲线
            $(document).on("click", "#add2", function () {
                global.get("/web/dataReport/devicesByProject/"+project.id,response=>{
                    var data=[];
                    response.data.devices.forEach(device=>{
                        var item={};
                        item.id=device.id;
                        item.text=device.name;
                        data.push(item);
                    });
                    Dialog.open({
                        title: "新增",
                        theme: "formDialog",
                        width: 480,
                        height: 320,
                        context: self,
                        content: template("dataFormTpl"),
                        onShow: function () {
                            $('#equipment').select2({
                                //  minimumResultsForSearch设置为-1，去除搜索框 
                                minimumResultsForSearch:-1,
                                placeholder:"请选择",
                                data: data
                            });
                        },
                        onClosed: function () {
                            if ($("#_idlg_mask_").length > 0) {
                                $("#_idlg_mask_").remove();
                            }
                        },
                        button: [{
                            id: "mybtn1",
                            label: "确定",
                            intent: "primary",
                            focus: true,
                            click: function () {
                                var name = $("#name").val();
                                    var equipment = $("#equipment").val();
                                    if(name==null || name.trim()==""){
                                        alert("请输入分类名");
                                        return;
                                    }
                                    var data = {}
                                    data.deviceId=equipment;
                                    data.categoryName=name;
                                    data.projectId=project.id;
                                    global.post("/web/dataReport/saveCategory",function(response){
                                        if(response.success){
                                            location.reload();
                                        }else{
                                            alert(response.message);
                                        }
                                    },JSON.stringify(data));
                            }
                        },
                            {
                                id: "mybtn2",
                                label: "取消",
                                intent: "default",
                                click: function () {
                                    this.close();
                                }
                            }
                        ],
                    });
                });
                
            })
            window.onresize = function () {
                // getTime.resize();
            };
        },
        
    };
    return app;
});